<?php
include_once 'common/Constant.class.php';
require_once SERVICE . DS . "admin" . DS . "CollectService.class.php";
class SetupController extends Controller{
	
	public function index(){
		$this->getSmarty();
        $this->smarty->assign ( 'pagesets', Constant::indexHeader() );
		$this->smarty->display("setup_serverinfo.tpl");
	}

    /**
     * 检验用户名，密码需要使用ajax，这样体验会好点
     */
    public function checkUserAndSiteId(){
        $usr = $_POST['user_name'];
        $pwd = $_POST['password'];
        $websitename = $_POST['websitename'];
       // $dbutil = $this->getMedooDb();

        $collectService = new CollectService(null,$usr, $pwd, $websitename);
        if($collectService->check_user($usr, $pwd, $websitename)){
            echo  json_encode(array("result"=>true));
        }else{
            echo  json_encode(array("result"=>false));
        }
    }
	public function validate(){
		$this->getSmarty();
        $usr = $_POST['user_name'];
        $pwd = $_POST['password'];
        $websitename = $_POST['websitename'];
       // $dbutil = $this->getMedooDb();

        $collectService = new CollectService(null,$usr, $pwd, $websitename);


		if($collectService->check_user()){
			// 服务端检查成功以后，获取用户的关键信息，用户id,网站id等
			$result = $collectService->getUserInfo();
  			$messageDto = json_decode($result);
			$userFile = PROJECT.DS.'framework'.DS."user.info";
			@file_put_contents($userFile,$messageDto->message);

            $this->smarty->display("setup_db.tpl");

		}else{
            $this->smarty->display("setup_serverinfo.tpl");
		}
	}
	
	public function execute(){
		$ip = $_POST['ip'];
		$database = $_POST['database'];
		$user = $_POST['user'];
		$pwd = $_POST['pwd'];
		$confFile = CORE.DS.'config.php';
		$String = file_get_contents($confFile.".tpl");
		//mysql config setup
		$String = str_replace('${db_host}',$ip,$String);
		$String = str_replace('${db_user}',$user,$String);
		$String = str_replace('${db_password}',$pwd,$String);
		$String = str_replace('${db_database}',$database,$String);
		//server config setup
		$userFile = PROJECT.DS.'framework'.DS."user.info";
		$userInfo = json_decode(file_get_contents($userFile));
		//project_website_name 与website_name的区别是，project_website_name必须以 / 结尾
		$websiteName = $userInfo->websiteName;
		$projectWebsitename = $websiteName;
		if(substr($projectWebsitename,-1) != '/' ){
			$projectWebsitename.='/';
		}
		$String = str_replace('${project_website_name}',$projectWebsitename,$String);
		$String = str_replace('${server_username}',$userInfo->username,$String);
		$String = str_replace('${server_pwd}',$userInfo->password,$String);
		$String = str_replace('${server_uid}',$userInfo->userId,$String);
		$String = str_replace('${website_name}',$websiteName,$String);
		$String = str_replace('${servier_wid}',$userInfo->websiteId,$String);



		file_put_contents($confFile, $String);
		
		//execute sql
		$sql = "";
		$sqlFile = MODEL.DS."setup.sql";
		if (file_exists($sqlFile)) {
			$sql = file_get_contents($sqlFile);

			try {
				$dbutil = new medoo(array(
					'database_type' => 'mysql',
					'server' => $ip,
					'username' => $user,
					'password' => $pwd
				));
			}catch (Exception $e) {
				echo $e->getMessage();
				$result = array('success'=>false,"error_message"=>$e->getMessage());
				echo json_encode ( $result );
				exit();
			}
			$sql = "drop database ".$database." ;";
		    $dbutil->query($sql);
		    
		    $sql = "create database ".$database." ;";
		    $dbutil->query($sql);
		    
		    $sql = "use ".$database." ;";
		    $dbutil->query($sql);

		    require_once SERVICE . DS . "admin" . DS . "DbService.class.php";
		    
		    $service = new DbService();
  

			$sql_query = file_get_contents($sqlFile);
		    $sql_query = $service->remove_remarks($sql_query); 
			$sql_query = $service->split_sql_file($sql_query, ';'); 
			foreach($sql_query as $sql){
				 $re=$dbutil->query($sql);
			}

			//将注册信息补充到卫星站管理后台

			$dbutil->insert('admin_users',
				array(
					'id'=>$userInfo->userId,
					'user_name'=>$userInfo->username,
					'real_name'=>$userInfo->username,
					'passwd'=>$userInfo->password
				)
			);
		}

		$result = array('success'=>true);
		echo json_encode ( $result );
	}
}